import axios from "axios"
import NProgress from "nprogress"

const CancelToken = axios.CancelToken
const source = CancelToken.source()

// 设置请求头和请求路径
axios.defaults.baseURL = "/api"
axios.defaults.timeout = 10000
axios.defaults.headers.post["Content-Type"] = "application/json;charset=UTF-8"
axios.interceptors.request.use(
  (config) => {
    var token = window.sessionStorage.getItem("token")
    if (token) {
      config.headers.token = token
    }
    return config
  },
  (error) => {
    return Promise.error(error)
  }
)
// 响应拦截
axios.interceptors.response.use((res) => {
  if (res.data.code === 111) {
    // token过期操作
  }
  return res
})
var uploadRequest = axios.create({
  baseURL: "/api",
  timeout: 10000,
  headers: { "Content-Type": "multipart/form-data" },
})
// 设置下载请求拦截
uploadRequest.interceptors.request.use(
  (config) => {
    var token = window.sessionStorage.getItem("token")
    if (token) {
      config.headers.token = token
    }
    return config
  },
  (error) => {
    return Promise.error(error)
  }
)
var http = {
  get(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .get(url, {
          params: params,
        })
        .then((res) => {
          console
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  post(url, params) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      axios
        .post(url, JSON.stringify(params))
        .then((res) => {
          NProgress.done()

          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  upload(url, file) {
    return new Promise((resolve, reject) => {
      NProgress.start()
      uploadRequest
        .post(url, file)
        .then((res) => {
          NProgress.done()
          resolve(res.data)
        })
        .catch((err) => {
          NProgress.done()
          reject(err.data)
        })
    })
  },
  download(url) {
    let iframe = document.createElement("iframe")
    iframe.style.display = "none"
    iframe.src = url
    iframe.onload = function () {
      document.body.removeChild(iframe)
    }
    document.body.appendChild(iframe)
  },
  install(app) {
    app.config.globalProperties["http"] = this
  },
}
export default http
